<template>
  <div class="address-container">
    <!-- 地址列表头部 -->
    <div class="address-header">
      <h2>收货地址</h2>
      <button class="add-btn" @click="showAddForm">+ 新增地址</button>
    </div>

    <!-- 地址列表 -->
    <div class="address-grid">
      <div
        v-for="(address, index) in addresses"
        :key="index"
        class="address-card"
        :class="{ 'default-card': address.isDefault === 1 }"
      >
        <div class="card-header">
          <div class="user-info">
            <span class="username">{{ address.recipient }}</span>
            <span class="phone">{{ address.mobile }}</span>
          </div>
          <div class="tags-container">
            <span v-if="address.isDefault === 1" class="default-tag">默认</span>
            <span v-if="address.remark" class="remark-tag"
              >备注: {{ address.remark }}</span
            >
          </div>
        </div>

        <div class="card-body">
          <div class="address-title">收货地址:</div>
          <div class="address-content">
            {{ address.address }} {{ address.detailedAddress }}
          </div>
        </div>

        <div class="card-footer">
          <button class="edit-btn" @click="editAddress(address)">✎ 编辑</button>
          <button
            class="default-btn"
            @click="setDefaultAddress(address.id)"
            v-if="address.isDefault !== 1"
          >
            ★ 设为默认
          </button>
          <button class="delete-btn" @click="deleteAddress(address.id)">
            × 删除
          </button>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorShow" class="no-address">
      <h1>{{ errorMsg }}</h1>
    </div>

    <!-- 新增/编辑地址表单 -->
    <div class="form-overlay" v-if="showForm">
      <div class="address-form">
        <div class="form-header">
          <h3>{{ formTitle }}</h3>
          <button class="close-btn" @click="hideForm">×</button>
        </div>
        <form @submit.prevent="submitForm">
          <div class="form-row">
            <div class="form-group">
              <label>收货人</label>
              <input
                type="text"
                v-model="formData.recipient"
                placeholder="请输入收货人姓名"
              />
            </div>
            <div class="form-group">
              <label>联系电话</label>
              <input
                type="tel"
                v-model="formData.mobile"
                placeholder="请输入联系电话"
              />
            </div>
          </div>

          <div class="form-group">
            <label>地址</label>
            <!-- 修改选择器部分，添加 key -->
            <div class="address-selectors">
              <select v-model="selectedProvince" @change="onProvinceChange">
                <option value="">请选择省份</option>
                <option
                  v-for="province in provinces"
                  :value="province.code"
                  :key="province.code"
                >
                  {{ province.name }}
                </option>
              </select>

              <select
                v-model="selectedCity"
                @change="onCityChange"
                :disabled="!selectedProvince"
              >
                <option value="">请选择城市</option>
                <option
                  v-for="city in cities"
                  :value="city.code"
                  :key="city.code"
                >
                  {{ city.name }}
                </option>
              </select>

              <select v-model="selectedDistrict" :disabled="!selectedCity">
                <option value="">请选择区县</option>
                <option
                  v-for="district in districts"
                  :value="district.code"
                  :key="district.code"
                >
                  {{ district.name }}
                </option>
              </select>
            </div>
          </div>

          <div class="form-group">
            <label>详细地址</label>
            <input
              type="text"
              v-model="formData.detailedAddress"
              placeholder="请输入详细地址（街道、门牌号等）"
            />
          </div>

          <div class="form-group">
            <label>备注</label>
            <input
              type="text"
              v-model="formData.remark"
              placeholder="请输入备注信息（选填）"
            />
          </div>

          <div class="form-actions">
            <button type="button" class="cancel-btn" @click="hideForm">
              取消
            </button>
            <button type="submit" class="submit-btn">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import areaData from "@/assets/area_format_object.json";
export default {
  name: "UserAddress",
  data() {
    return {
      errorShow: false,
      errorMsg: "",
      addresses: [],
      showForm: false,
      isEditing: false,
      currentAddressId: null,
      formData: {
        recipient: "",
        mobile: "",
        address: "",
        detailedAddress: "",
        remark: "",
        isDefault: 0,
      },
      areaData: areaData,
      provinces: [],
      cities: [],
      districts: [],
      selectedProvince: "",
      selectedCity: "",
      selectedDistrict: "",
    };
  },
  computed: {
    formTitle() {
      return this.isEditing ? "编辑收货地址" : "新增收货地址";
    },
  },
  created() {
    this.loadAddresses();
    this.initProvinces();
  },
  methods: {
    initProvinces() {
      this.provinces = Object.entries(this.areaData).map(([code, info]) => ({
        code,
        name: info.n,
        letter: info.y,
      }));
    },
    async loadAddresses() {
      try {
        const response = await axios.get(
          `/api/address/getAllAddress`
        );

        if (response.data.code === 200) {
          let addresses = response.data.data || [];
          const hasDefault = addresses.some((addr) => addr.isDefault === 1);

          if (!hasDefault && addresses.length > 0) {
            this.errorMsg = "请设置一个默认地址";
            this.errorShow = true;
          }

          this.addresses = addresses;
          this.errorShow = this.addresses.length === 0;
          if (this.addresses.length === 0) {
            this.errorMsg = '您还没有保存收货地址，请点击"新增地址"添加';
          }
        } else {
          console.error("获取地址失败:", response.data.msg);
          this.errorMsg = response.data.msg;
          this.errorShow = true;
        }
      } catch (error) {
        console.error("获取地址失败:", error);
        this.errorMsg = "获取地址失败，请稍后重试";
        this.errorShow = true;
      }
    },
    async showAddForm() {
      try {
        const response = await axios.get(
          `/api/address/checkAddressNum`
        );
        if (response.data.code === 500) {
          alert(response.data.msg);
          return;
        }
      } catch (error) {
        console.log(error);
      }
      this.isEditing = false;
      this.resetForm();
      this.showForm = true;
    },
    editAddress(address) {
      this.isEditing = true;
      this.currentAddressId = address.id;
      this.formData = {
        recipient: address.recipient,
        mobile: address.mobile,
        address: address.address,
        detailedAddress: address.detailedAddress,
        remark: address.remark,
        isDefault: address.isDefault,
      };
      this.setSelectedAreas(address.address);
      this.showForm = true;
    },
    hideForm() {
      this.showForm = false;
    },
    resetForm() {
      this.formData = {
        recipient: "",
        mobile: "",
        address: "",
        detailedAddress: "",
        remark: "",
        isDefault: 0,
      };
      this.selectedProvince = "";
      this.selectedCity = "";
      this.selectedDistrict = "";
      this.cities = [];
      this.districts = [];
    },
    // 省份变化时加载城市
    onProvinceChange() {
      const province = this.areaData[this.selectedProvince];
      this.cities = Object.entries(province.c || {}).map(([code, info]) => ({
        code,
        name: info.n,
        letter: info.y,
      }));
      this.selectedCity = "";
      this.selectedDistrict = "";
      this.districts = [];
      this.updateAddressString();
    },

    // 城市变化时加载区县
    onCityChange() {
      const city = this.areaData[this.selectedProvince].c[this.selectedCity];
      this.districts = Object.entries(city.c).map(([code, info]) => ({
        code,
        name: info.n,
        letter: info.y,
      }));
      this.selectedDistrict = "";
      this.updateAddressString();
    },

    // 更新地址字符串
    updateAddressString() {
      const province = this.areaData[this.selectedProvince].n;
      const city = this.areaData[this.selectedProvince].c[this.selectedCity].n;
      const district =
        this.areaData[this.selectedProvince].c[this.selectedCity].c[
          this.selectedDistrict
        ].n;

      this.formData.address = `${province},${city},${district}`;
    },

    setSelectedAreas(addressStr) {
      console.log("地址字符串:", addressStr);
      if (!addressStr) return;

      // 重置选择器
      this.selectedProvince = "";
      this.selectedCity = "";
      this.selectedDistrict = "";
      this.cities = [];
      this.districts = [];

      const [provinceName, cityName, districtName] = addressStr.split(",");
      if (!provinceName || !cityName || !districtName) {
        console.error("地址格式错误，需为'省,市,区'");
        return;
      }

      // 查找省份
      for (const [provinceCode, provinceInfo] of Object.entries(
        this.areaData
      )) {
        if (provinceInfo.n === provinceName) {
          this.selectedProvince = provinceCode;
          // 更新城市列表 - 保持与 onProvinceChange 一致的格式
          this.cities = Object.entries(provinceInfo.c || {}).map(
            ([code, city]) => ({
              code,
              name: city.n,
            })
          );

          // 查找匹配的城市
          for (const [cityCode, cityInfo] of Object.entries(
            provinceInfo.c || {}
          )) {
            if (cityInfo.n === cityName) {
              this.selectedCity = cityCode;
              // 更新区县列表 - 保持与 onCityChange 一致的格式
              this.districts = Object.entries(cityInfo.c || {}).map(
                ([code, district]) => ({
                  code,
                  name: district.n,
                })
              );

              // 查找匹配的区县
              for (const [districtCode, districtInfo] of Object.entries(
                cityInfo.c || {}
              )) {
                if (districtInfo.n === districtName) {
                  this.selectedDistrict = districtCode;
                  break;
                }
              }
              break;
            }
          }
          break;
        }
      }
    },
    async submitForm() {
      try {
        // 验证必填字段
        if (!this.formData.recipient || !this.formData.mobile) {
          this.$message.error("收货人和电话不能为空");
          return;
        }
        // 手机号格式验证
        const mobileRegex = /^1[3-9]\d{9}$/;
        if (!mobileRegex.test(this.formData.mobile)) {
          this.$message.error("请输入正确的手机号码");
          return;
        }

        // 确保地址选择完成
        if (
          !this.selectedProvince ||
          !this.selectedCity ||
          !this.selectedDistrict
        ) {
          this.$message.error("请选择完整的省市区");
          return;
        }

        if (!this.formData.detailedAddress) {
          this.$message.error("请填写具体地址");
          return;
        }
        // 更新地址字符串
        this.updateAddressString();

        const requestData = {
          ...this.formData,
        };

        let url, method;
        if (this.isEditing) {
          url = "/api/address/updateAddress";
          requestData.id = this.currentAddressId;
          method = "post";
        } else {
          url = "/api/address/addAddress";
          method = "post";
        }
        const response = await axios({
          method,
          url,
          data: requestData,
        });

        if (response.data.code === 200) {
          this.$message.success(response.data.msg || "操作成功");
          this.loadAddresses();
          this.hideForm();
        } else if (response.data.code === 500) {
          alert("操作失败:" + response.data.msg);
        } else {
          throw new Error(response.data.message || "操作失败");
        }
      } catch (error) {
        console.error("操作失败:", error);
        this.$message.error(
          error.response?.data?.message ||
            error.message ||
            "网络错误，请稍后重试"
        );
      }
    },
    async setDefaultAddress(id) {
      try {
        const response = await axios.get(
          `/api/address/setDefault/${id}`
        );
        if (response.data.code === 200) {
          this.loadAddresses();
          this.$message.success("设置默认地址成功");
        } else {
          throw new Error(response.data.message || "设置默认地址失败");
        }
      } catch (error) {
        console.error("设置默认地址失败:", error);
        this.$message.error(error.message || "网络错误，请稍后重试");
      }
    },
    async deleteAddress(id) {
      try {
        await this.$confirm("确定要删除这个地址吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        const response = await axios.delete(`/api/address/deleteAddress/${id}`);
        if (response.data.code === 200) {
          this.$message.success("地址删除成功");
          this.loadAddresses();
        } else {
          throw new Error(response.data.message || "删除地址失败");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除地址失败:", error);
          this.$message.error(error.message || "网络错误，请稍后重试");
        }
      }
    },
  },
};
</script>

<style scoped>
.address-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}

/* 头部样式 */
.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.address-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.add-btn {
  background-color: #ff6700;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.add-btn:hover {
  background-color: #ff8533;
}

/* 调整网格布局 */
.address-grid {
  display: grid;
  grid-template-columns: repeat(
    auto-fill,
    minmax(300px, 1fr)
  ); /* 自动填充，最小300px */
  gap: 20px;
}

/* 地址卡片样式 */
.address-card {
  width: 300px; /* 固定宽度 */
  height: 200px; /* 固定高度 */
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 15px;
  background-color: white;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.address-card:hover {
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
  border-color: #ffd1ac;
}

.default-card {
  border: 2px solid #ff6700;
  background-color: #fff8f0;
  position: relative;
}

.default-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  border-top: 30px solid #ff6700;
  border-right: 30px solid transparent;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.username {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.phone {
  font-size: 14px;
  color: #666;
}

.tags-container {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.default-tag {
  background-color: #ff6700;
  color: white;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
}

.remark-tag {
  background-color: #f5f5f5;
  color: #666;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  white-space: nowrap;
}

/* 卡片主体 */
.card-body {
  margin-bottom: 15px;
}

.address-title {
  font-size: 14px;
  color: #999;
  margin-bottom: 5px;
}

.address-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  height: 42px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 卡片底部操作按钮 */
.card-footer {
  display: flex;
  justify-content: space-between;
  padding-top: 10px;
  border-top: 1px dashed #f0f0f0;
}

.card-footer button {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 13px;
  padding: 0;
}

.card-footer button:hover {
  color: #ff6700;
}

.delete-btn:hover {
  color: #ff3333;
}

/* 无地址提示 */
.no-address {
  text-align: center;
  padding: 80px 0;
  color: #999;
}

.no-address h1 {
  font-size: 18px;
  font-weight: normal;
  margin: 0;
}

/* 表单样式 */
.form-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.address-form {
  background-color: white;
  border-radius: 8px;
  width: 550px;
  max-width: 90%;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.2);
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.form-header h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #666;
}

form {
  padding: 20px;
}

.form-row {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.form-group {
  flex: 1;
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.form-group input {
  width: 70%;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.form-group input:focus {
  border-color: #ff6700;
  outline: none;
}

.checkbox-group {
  display: flex;
  align-items: center;
}

.checkbox-group input {
  width: auto;
  margin-right: 8px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #e0e0e0;
}

.cancel-btn:hover {
  background-color: #eee;
}

.submit-btn {
  background-color: #ff6700;
  color: white;
  border: none;
}

.submit-btn:hover {
  background-color: #ff8533;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .address-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .address-grid {
    grid-template-columns: 1fr;
  }

  .form-row {
    flex-direction: column;
    gap: 0;
  }
}

.address-selectors {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.address-selectors select {
  width: 150px;
  padding: 6px 10px;
  border: 1px solid #d9d9d9;
  border-radius: 3px;
  background-color: #fff;
  color: #333;
  font-size: 14px;
  height: 36px;
  line-height: 1.5;
}

.address-selectors select:disabled {
  background-color: #f0f0f0;
  color: #999;
}
</style>